package com.gitee.cirnochat.file.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.cirnochat.common.exception.BusinessException;
import com.gitee.cirnochat.common.model.enums.ErrorCode;
import com.gitee.cirnochat.common.utils.FileUtil;
import com.gitee.cirnochat.file.model.entity.EmojiPack;
import com.gitee.cirnochat.file.model.entity.EmojiPackItem;
import com.gitee.cirnochat.file.model.entity.EmojiPackItemDetail;
import com.gitee.cirnochat.file.model.enums.FileType;
import com.gitee.cirnochat.file.model.vo.req.EmojiPackItemUpdateRequest;
import com.gitee.cirnochat.file.model.vo.resp.*;
import com.gitee.cirnochat.file.service.EmojiPackItemService;
import com.gitee.cirnochat.file.service.EmojiPackService;
import com.gitee.cirnochat.file.mapper.EmojiPackMapper;
import com.gitee.cirnochat.file.service.FileManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;

/**
* @author FlanChan
* @description 针对表【emoji_pack(表情包表)】的数据库操作Service实现
* @createDate 2025-07-01 16:07:04
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class EmojiPackServiceImpl extends ServiceImpl<EmojiPackMapper, EmojiPack>
    implements EmojiPackService{

    private final FileManager fileManager;
    private final EmojiPackItemService emojiPackItemService;

    @Override
    public List<EmojiPackResponse> listUserEmojiPacks(Long userId) {
        List<EmojiPack> list = this.list(new LambdaQueryWrapper<>(EmojiPack.class)
                .eq(EmojiPack::getUserId, userId)
                .orderByDesc(EmojiPack::getCreateTime));
        return list.isEmpty() ? List.of() : list.stream().map(EmojiPackResponse::new).toList();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public EmojiPackItemCreateResponse uploadEmojiPack(MultipartFile file, Long userId) {
        FileType fileTypeByContentType = FileUtil.getFileTypeByContentType(file.getContentType());
        log.info("上传的文件类型: {}, 文件大小: {}", fileTypeByContentType, file.getSize());
        if (fileTypeByContentType != FileType.IMAGE) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "上传的文件类型不正确，请上传图片文件");
        }
        if (file.getSize() > 10 * 1024 * 1024) { // 限制文件大小为10MB
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "上传的文件过大，请上传小于10MB的图片");
        }
        //查询当前表情包数据是否存在
        EmojiPack emojiPack = this.getOne(new LambdaQueryWrapper<EmojiPack>()
                .eq(EmojiPack::getUserId, userId));
        LocalDateTime updateTime = LocalDateTime.now();
        if (emojiPack == null) {
            // 如果不存在，则创建新的表情包
            emojiPack = new EmojiPack();
            emojiPack.setId(IdWorker.getId());
            emojiPack.setUserId(userId);
            emojiPack.setEmojiCount(0);
            emojiPack.setCreateTime(updateTime);
            emojiPack.setUpdateTime(updateTime);
            this.save(emojiPack);
        } else {
            emojiPack.setEmojiCount(emojiPack.getEmojiCount() + 1);
            emojiPack.setUserId(userId);
            emojiPack.setCreateTime(updateTime);
            emojiPack.setUpdateTime(updateTime);
            this.updateById(emojiPack);
        }
        // 储存表情包
        FileUploadResponse fileUploadResponse = fileManager.uploadFile(file);
        EmojiPackItem emojiPackItem = new EmojiPackItem();
        emojiPackItem.setFileId(fileUploadResponse.getFileId());
        emojiPackItem.setEmojiPackId(emojiPack.getId());
        emojiPackItem.setCreateTime(updateTime);
        emojiPackItem.setUpdateTime(updateTime);
        emojiPackItemService.save(emojiPackItem);
        return new EmojiPackItemCreateResponse(emojiPackItem,fileUploadResponse);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public EmojiPackItemUpdateResponse deleteEmojiItem(Long emojiId, Long userId) {
        //如果该表情包项不存在，直接返回-1
        EmojiPackItem emojiPackItem = emojiPackItemService.getOne(new LambdaQueryWrapper<EmojiPackItem>()
                .eq(EmojiPackItem::getId, emojiId));
        if (emojiPackItem == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"表情包项不存在");
        }
        //如果该表情包项的表情包是预置表情包，直接返回-1
        EmojiPack emojiPack = this.getOne(new LambdaQueryWrapper<>(EmojiPack.class)
                .eq(EmojiPack::getId, emojiPackItem.getEmojiPackId())
                .eq(EmojiPack::getUserId, userId));
        if (emojiPack == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"表情包不存在");
        }
        // 删除表情包项
        emojiPackItemService.removeById(emojiId);
        // 更新表情包的表情数量
        LocalDateTime updateTime = LocalDateTime.now();
        emojiPack.setEmojiCount(emojiPack.getEmojiCount() - 1);
        emojiPack.setUpdateTime(updateTime);
        this.updateById(emojiPack);
        // 返回更新时间戳
        return new EmojiPackItemUpdateResponse(emojiPackItem);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public EmojiPackItemUpdateResponse updateEmojiItem(EmojiPackItemUpdateRequest req, Long userId) {
        if (req == null || req.getId() == null) {
            return null;
        }
        EmojiPackItem emojiPackItem = emojiPackItemService.getById(req.getId());
        if (emojiPackItem == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"表情包项不存在");
        }
        EmojiPack emojiPack = this.getById(emojiPackItem.getEmojiPackId());
        if (emojiPack == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"表情包不存在");
        }
        // 更新时间戳
        LocalDateTime updateTime = LocalDateTime.now();
        // 更新 EmojiPackItem 的字段
        emojiPackItem.setSortOrder(req.getSortOrder());
        emojiPackItem.setUpdateTime(updateTime);
        emojiPackItemService.updateById(emojiPackItem);
        emojiPack.setUpdateTime(updateTime);
        this.updateById(emojiPack);
        return new EmojiPackItemUpdateResponse(emojiPackItem);
    }

    @Override
    public List<EmojiPackItemResponse> listUserEmojis(Long userId) {
        List<EmojiPackItemDetail> items = emojiPackItemService.listUserEmojiPackItems(userId);
        return items.isEmpty() ? List.of() : items.stream()
                .map(EmojiPackItemResponse::new)
                .toList();
    }

    @Override
    public EmojiPackResponse getUserEmojiPack(Long userId) {
        EmojiPack emojiPack = this.getOne(new LambdaQueryWrapper<EmojiPack>()
                .eq(EmojiPack::getUserId, userId));
        LocalDateTime updateTime = LocalDateTime.now();
        if (emojiPack == null) {
            // 如果不存在，则创建新的表情包
            emojiPack = new EmojiPack();
            emojiPack.setId(IdWorker.getId());
            emojiPack.setUserId(userId);
            emojiPack.setEmojiCount(0);
            emojiPack.setCreateTime(updateTime);
            emojiPack.setUpdateTime(updateTime);
            System.out.println(emojiPack);
            this.save(emojiPack);
        }
        return new EmojiPackResponse(emojiPack);
    }
}




